<!-- subpkg_consult/payment/index.vue -->
<script lang="ts" setup>
  import { createOrderApi, orderPayApi, preOrderApi } from '@/apis/consult'
  import { patientDetailApi } from '@/apis/patient'
  import { useConsultStore } from '@/stores/consult'
  import type { OrderPreData } from '@/types/consult'
  import { PatientItem } from '@/types/patient'
  import { ref } from 'vue'

  // 创建预付订单信息
  // 患者相关的数据（不具有响应性）
  const store = useConsultStore()
  // 预付订单信息
  const preOrderInfo = ref({} as OrderPreData)

  // 生成预付订单
  const createPreOrder = async () => {
    // 预付订单信息
    const data = await preOrderApi({ type: store.type, illnessType: store.illnessType })
    // 渲染订单数据
    preOrderInfo.value = data
  }
  // 调用生成预付订单接口
  createPreOrder()

  // 就诊患者信息
  const patientDetail = ref({} as PatientItem)
  // 获取患者信息
  const getPatientDetail = async () => {
    // 患者详情接口
    const data = await patientDetailApi(store.patientId)
    // 渲染患者数据
    patientDetail.value = data
  }
  // 获取就诊患者信息
  getPatientDetail()

  // 生成订单
  // 订单ID
  const orderId = ref('')
  // 立即支付
  const onPaymentButtonClick = async () => {
    if (orderId.value !== '')
      return uni.showToast({
        title: '订单不能重复创建！',
      })

    // 生成订单接口
    const data = await createOrderApi({
      type: store.type,
      illnessType: store.illnessType,
      patientId: store.patientId,
      depId: store.depId,
      illnessDesc: store.consultInfo.illnessDesc,
      illnessTime: store.consultInfo.illnessTime,
      consultFlag: store.consultInfo.consultFlag,
      pictures: store.consultInfo.pictures,
    })

    // 接收订单ID
    orderId.value = data.id

    // 将 Pinia 中缓存的数据清空掉（订单已创建完成）
    store.clear()
  }

  // 当支付弹层关闭时
  const onPaymentClose = async () => {
    const { confirm } = await uni.showModal({
      title: '关闭支付',
      content: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
      cancelText: '仍要关闭',
      cancelColor: '#848484',
      confirmText: '继续支付',
      confirmColor: '#16C2A3',
    })

    if (!confirm) {
      // paymentRef.value.close()
      uni.reLaunch({
        url: '/pages/index/index',
      })
    }
  }

  const currnetIndex = ref(0)
  // 5. 支付
  const onPaymentConfirm = async (index: number) => {
    if (index === 0)
      return uni.showToast({
        title: '暂不支持微信支付!',
      })
    currnetIndex.value = index
  }
  // 调用后端提供的支付接口
  const { payUrl } = await orderPayApi({
    orderId: orderId.value,
    paymentMethod: currnetIndex + '',
    payCallback: 'http://localhost:5173/#/subpkg_consult/room/index',
  })

  // #ifdef H5
  // 引导用户支付（地址跳转方式）
  window.location.href = payUrl
  // #endif

  // #ifdef MP-WEIXIN
  // 引导用户支付（wx.requestPayment 小程序）
  // wx.requestPayment({
  //   // 4 个参数
  // })
  // #endif
</script>

<template>
  <scroll-page>
    <view class="payment-page">
      <uni-section
        title-font-size="32rpx"
        title-color="#121826"
        padding="30rpx"
        :title="`图文问诊 ${preOrderInfo.payment}元`"
      >
        <uni-list :border="false">
          <uni-list-item
            title="极速问诊"
            note="自动分配医生"
            thumb="/static/uploads/doctor-avatar.jpg"
            thumb-size="lg"
          />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${preOrderInfo.couponDeduction}`"
          />
          <uni-list-item title="积分抵扣">
            <template #footer>
              <view class="uni-list-text-red">-¥{{ preOrderInfo.pointDeduction }}</view>
            </template>
          </uni-list-item>
          <uni-list-item title="实付款">
            <template #footer>
              <view class="uni-list-text-red">¥{{ preOrderInfo.actualPayment }}</view>
            </template>
          </uni-list-item>
        </uni-list>
      </uni-section>

      <view class="dividing-line"></view>

      <uni-section title-font-size="32rpx" title-color="#121826" padding="30rpx" title="患者资料">
        <uni-list :border="false">
          <uni-list-item title="患者信息">
            <template #footer>
              <view class="uni-list-text-gray">
                {{ patientDetail.name }} | {{ patientDetail.genderValue }} |
                {{ patientDetail.age }}岁
              </view>
            </template>
          </uni-list-item>
          <uni-list-item border title="病情描述" note="头痛,头晕,恶心" />
        </uni-list>
      </uni-section>

      <!-- <view class="payment-agreement">
        <radio color="#20c6b2" value="1" />
        我已同意<text style="color: #20c6b2">支付协议</text>
      </view> -->
    </view>
    <!-- 下一步操作 -->
    <view class="next-step">
      <view class="total-amount">
        合计: <text class="number">¥{{ preOrderInfo.actualPayment }}</text>
      </view>
      <button class="uni-button" @click="onPaymentButtonClick">立即支付</button>
    </view>
  </scroll-page>
  <consult-payment
    :amount="preOrderInfo.actualPayment"
    :order-id="orderId"
    ref="paymentRef"
    @confirm="onPaymentConfirm"
    @close="onPaymentClose"
  >
  </consult-payment>
</template>

<style lang="scss">
  @import './index.scss';
</style>
